package com.mexico.inloancash.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustAttribution;
import com.facebook.appevents.AppEventsLogger;
import com.mexico.inloancash.dialog.India_User_Agreement_CommonDialog;
import com.mexico.inloancash.fragment.IndiaPersonalFragment;
import com.mexico.inloancash.utils.GetJsonDataUtil;
import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.India_Address_ListBean;
import com.mexico.inloancash.dialog.India_UserNotice_CommonDialog;
import com.mexico.inloancash.fragment.IndiaFirstPageFragment;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements IndiaDealDialogInterface {

    @BindView(R.id.frame_layout)
    FrameLayout mIndiaFrameLayout;

    @BindView(R.id.first_page)
    TextView mIndiaFirstTvPage;

    @BindView(R.id.mine_page)
    TextView mIndiaIneTvPage;

    private List<Fragment> mIndiaFragmentArrayList = new ArrayList<>();
    private India_UserNotice_CommonDialog dialog;
    //记录用户首次点击返回键的时间
    private long firstTime = 0;
    public static boolean isShow = false;//判断是否有提交过申请

    private India_User_Agreement_CommonDialog userAgreementCommonDialog;

    Timer timer = new Timer();
    TimerTask mIndiaCountDownTask;

    AppEventsLogger mIndiaLogger;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.india_activity_view_main);
        immersive();
        ButterKnife.bind(this);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        mIndiaLogger = AppEventsLogger.newLogger(this);

        //进入主页面 弹出协议弹窗只有在第一次进入才弹出------------------------2021-4-16改
        //2021-6-17 第一次进入app 不谈弹出app隐私协议
       /* if(!MyPreferencesManager.getIsShow()){
            userAgreementCommonDialog =new UserAgreementCommonDialog(this);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    userAgreementCommonDialog.show();
                }
            },1000);
        }*/
        //进入主页面 弹出协议弹窗---------------------------------------------2021-4-16改

        //首页
        mIndiaFragmentArrayList.add(new IndiaFirstPageFragment());
        //个人主页
        mIndiaFragmentArrayList.add(new IndiaPersonalFragment());
        MyPreferencesManager.putString("address", new GetJsonDataUtil().getJsonData(this, "address.json"));
        getSupportFragmentManager().beginTransaction().add(R.id.frame_layout, mIndiaFragmentArrayList.get(0)).add(R.id.frame_layout, mIndiaFragmentArrayList.get(1)).hide(mIndiaFragmentArrayList.get(1)).show(mIndiaFragmentArrayList.get(0)).commit();
        India_SetIndex_CurrentTab(0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                India_isFirst_Open_App();
            }
        },2000);

        //获取归因 存在一次拿不到值情况  定时任务获取 30 次
        if(TextUtils.isEmpty(MyPreferencesManager.getTrackerName())){
            India_get_Task();
        }
    }

    private volatile int count = 0;

    void India_get_Task() {
        if (mIndiaCountDownTask != null) {
            mIndiaCountDownTask.cancel();
        }
        mIndiaCountDownTask = new TimerTask() {
            @Override
            public void run() {
                count++;
                AdjustAttribution attribution = Adjust.getAttribution();
                //Log.e("data","第"+count+"次调用"+attribution);
                //Message message=handler.obtainMessage();
                //message.what=count;
                //handler.sendMessage(message);
                if(attribution!=null){
                    if(!TextUtils.isEmpty(attribution.trackerName)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                MyPreferencesManager.putTrackerName(attribution.trackerName);
                                //Log.e("data","拿到值了"+attribution.trackerName);
                                Indias_top_Task();
                                //Toast.makeText(MainActivity.this,"拿到值了"+attribution.trackerName,Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
                if (count == 3) {
                    mIndiaCountDownTask.cancel();
                    //Log.e("data","3次次数已到 不拿值了");
                    count=0;
                }
            }
        };
        timer.schedule(mIndiaCountDownTask, 2000, 3000);//延时两秒后 每隔两秒获取一次
    }

    void Indias_top_Task() {
        if (timer != null) {
            timer.cancel();
            count=0;
            //Log.e("data","停止拿值");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Indias_top_Task();
    }


    private void India_isFirst_Open_App() {
        int first = MyPreferencesManager.getInt("express.FIRST_OPEN", 0);
        Log.d("loan", "firstOpen:" + first);
        if (first == 0) {
            MyPreferencesManager.putInt("express.FIRST_OPEN", 1);
            //2021-4-14添加 统计安装数量
            India_Count_Install();
        }
    }

    /**
     * 统计应用安装(第一次进入应用视为第一次安装)
     */
    public void India_Count_Install() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getAddr = api.getInstall(MyApplication.source);
        getAddr.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {

                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                MyToast.show(MainActivity.this, "Press again to exit the program");
                firstTime = secondTime;
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (MyPreferencesManager.getLogin()) {
            if (TextUtils.isEmpty(MyPreferencesManager.getString("bank", "")) || TextUtils.isEmpty(MyPreferencesManager.getString("address", ""))) {
                India_Get_NewAddress();
            }
        } else {
            India_SetIndex_CurrentTab(0);
        }
    }

    public int currentTabIndex = 0;

    public void India_SetIndex_CurrentTab(int indext) {
        if (currentTabIndex != indext) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(mIndiaFragmentArrayList.get(currentTabIndex));
            if (!mIndiaFragmentArrayList.get(indext).isAdded()) {
                trx.add(R.id.frame_layout, mIndiaFragmentArrayList.get(indext));
            }
            trx.show(mIndiaFragmentArrayList.get(indext)).commit();
        }
        if (indext == 0) {
            mIndiaFirstTvPage.setSelected(true);
            mIndiaIneTvPage.setSelected(false);
        } else {
            mIndiaFirstTvPage.setSelected(false);
            mIndiaIneTvPage.setSelected(true);
        }
        currentTabIndex = indext;
    }

    @OnClick({R.id.first_page, R.id.mine_page})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.first_page:
                India_SetIndex_CurrentTab(0);
                break;
            case R.id.mine_page:
                if (MyPreferencesManager.getLogin()) {
                    India_SetIndex_CurrentTab(1);
                } else {
//                    if (TextUtils.isEmpty(MyPreferencesManager.getString("isFirst", ""))) {
//                        dialog = new India_UserNotice_CommonDialog(MainActivity.this, MainActivity.this);
//                        dialog.show();
//                    } else {
                        Intent login = new Intent(this, IndiaLoginActivity.class);//登陆
                        startActivity(login);
                   // }
                }
                break;
        }
    }


    public void India_Get_NewAddress() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getAddr = api.getAddress();
        getAddr.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {
                        India_Address_ListBean indiaAddressListBean = new Gson().fromJson(response.body(), India_Address_ListBean.class);
                        if (indiaAddressListBean.getStatus() == 1) {
                            MyPreferencesManager.putString("address", response.body());
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }


    @Override
    public void doPlay() {
        Intent login = new Intent(this, IndiaLoginActivity.class);//登陆
        startActivity(login);
    }

    @Override
    public void choose() {

    }
}
